package T回溯;

import java.util.LinkedList;
import java.util.List;

/**
 * @author tmh
 * @date 2023/10/17 17:08
 * @description T_131分割回文串
 */
public class T_131分割回文串 {
    List<List<String>> result = new LinkedList<>();
    LinkedList<String> path = new LinkedList<>();

    public List<List<String>> partition(String s) {
        backTracking(s, 0);
        return result;
    }

    private void backTracking(String s, int startIndex) {
        //终止条件
        if (startIndex >= s.length()) {
            result.add(new LinkedList<>(path));
            return;
        }
        for (int i = startIndex; i < s.length(); i++) {
            if (isPalindrome(s, startIndex, i)) {
                String str = s.substring(startIndex, i + 1);
                path.add(str);
            } else {
                continue;
            }
            backTracking(s, i + 1);
            path.removeLast();
        }
    }

    //判断是否是回文字符串
    private boolean isPalindrome(String s, int start, int end) {
        for (int i = start, j = end; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        T_131分割回文串 t = new T_131分割回文串();
        List<List<String>> result = t.partition("aab");
        System.out.println(result);
    }

}
